import axios from 'axios'
import { Base64 } from 'js-base64'
import { ElMessage, ElNotification, ElMessageBox } from 'element-plus'
import useUserStore from '@/stores/useUserStore.js'

const request = axios.create({
  baseURL: import.meta.env.VITE_BASEURL
})

request.interceptors.request.use((config) => {
  const userStore = useUserStore()
  if (userStore.token) {
    config.headers.Authorization = 'Basic ' + Base64.encode(userStore.token + ':')
  }
  return config
}, (err) => {
  return Promise.reject(err)
})

request.interceptors.response.use((res) => {
  return res.data
}, (err) => {
  const userStore = useUserStore()
  switch (err.status) {
    case 422:
      ElMessage({ type: 'info', message: err.response.data.msg, duration: 1000 })
      break
    case 401:
      if (err.response.data.code === 4001) {
        ElNotification({
          title: '提示',
          message: err.response.data.msg,
          type: 'warning',
          duration: 1000
        })
      }
      else {
        ElMessageBox.confirm(
          err.response.data.msg,
          '提示',
          {
            confirmButtonText: '我知道了',
            showClose: false,
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false,
            type: 'warning',
          }
        )
          .then(() => {
            userStore.deleteToken()
            userStore.deleteUser()
            window.location.href = '/'
          })
      }
      break
  }
  return Promise.reject(err)
})

export default request